{% extends "base.html" %}

{% block title %}计数与复制应用{% endblock %}

{% block extra_css %}
<style type="text/tailwindcss">
    @layer utilities {
        .content-auto {
            content-visibility: auto;
        }
        .app-display-box {
            @apply bg-white rounded-lg shadow-md p-4 text-2xl font-bold text-center transition-all duration-300 border-2 border-blue-100 cursor-text;
        }
        .app-display-box-editable {
            @apply border-blue-500 bg-blue-50;
        }
        .app-ratio-box {
            @apply bg-white rounded-lg shadow-md p-4 text-2xl font-bold text-center transition-all duration-300 border-2 border-purple-100;
        }
        .app-btn-primary {
            @apply bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 shadow-md hover:shadow-lg transform hover:-translate-y-0.5 focus:outline-none focus:ring-2 focus:ring-blue-500/50;
        }
        .app-btn-secondary {
            @apply bg-purple-600 hover:bg-purple-700 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 shadow-md hover:shadow-lg transform hover:-translate-y-0.5 focus:outline-none focus:ring-2 focus:ring-purple-500/50;
        }
        .app-btn-minus {
            @apply bg-gray-600 hover:bg-gray-700 text-white font-medium py-1 px-3 rounded-lg transition-all duration-300 text-sm;
        }
        .app-btn-back {
            @apply bg-gray-600 hover:bg-gray-700 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 shadow-md hover:shadow-lg flex items-center;
        }
        .app-input-field {
            @apply border-2 border-gray-300 rounded-lg px-4 py-2 text-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300;
        }
        .app-animate-shake {
            animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
        }
        @keyframes shake {
            10%, 90% { transform: translateX(-1px); }
            20%, 80% { transform: translateX(2px); }
            30%, 50%, 70% { transform: translateX(-3px); }
            40%, 60% { transform: translateX(3px); }
        }

        /* 弹窗样式 */
        .app-toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%) translateY(-100px);
            padding: 12px 24px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            opacity: 0;
            transition: all 0.3s ease;
        }

        .app-toast.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }

        .app-toast.success {
            background-color: #10B981;
        }

        .app-toast.error {
            background-color: #EF4444;
        }

        .app-toast.info {
            background-color: #3B82F6;
        }

        /* 编辑输入框样式 */
        .app-edit-input {
            width: 100%;
            background: transparent;
            border: none;
            text-align: center;
            font-size: inherit;
            font-weight: inherit;
            color: inherit;
            padding: 0;
            margin: 0;
            outline: none;
        }

        .app-counter-container {
            @apply flex flex-col;
        }

        .app-counter-display {
            @apply flex items-center justify-center gap-2;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <!-- 返回按钮 -->
    <button id="backButton" class="app-btn-back mb-6">
        <i class="fa fa-arrow-left mr-2"></i> 返回上一页
    </button>

    <!-- 弹窗提示元素 -->
    <div id="toast" class="app-toast"></div>

    <div class="max-w-2xl w-full bg-white rounded-xl shadow-xl p-6 md:p-8 transform transition-all duration-500 hover:shadow-2xl mx-auto">
        <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-center text-gray-800 mb-6">计数与复制应用</h1>

        <!-- 显示区域 -->
        <div class="grid grid-cols-1 gap-6 mb-8">
            <!-- 第一行：框数、错误数、帧数 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                <!-- 框数显示（可编辑） -->
                <div class="app-counter-container">
                    <label for="boxCount" class="text-sm text-gray-600 mb-1 text-center">框数 <span class="text-xs opacity-70">(可编辑)</span></label>
                    <div class="app-counter-display">
                        <div id="boxCount" class="app-display-box flex-1" data-value="0">0</div>
                        <button id="boxMinusBtn" class="app-btn-minus">
                            <i class="fa fa-minus"></i>
                        </button>
                    </div>
                </div>

                <!-- 错误数显示 -->
                <div class="flex flex-col">
                    <label for="errorCount" class="text-sm text-gray-600 mb-1 text-center">错误数</label>
                    <div id="errorCount" class="app-display-box" data-value="0">0</div>
                </div>

                <!-- 帧数显示（可编辑） -->
                <div class="app-counter-container">
                    <label for="frameCount" class="text-sm text-gray-600 mb-1 text-center">帧数 <span class="text-xs opacity-70">(可编辑)</span></label>
                    <div class="app-counter-display">
                        <div id="frameCount" class="app-display-box flex-1" data-value="0">0</div>
                        <button id="frameMinusBtn" class="app-btn-minus">
                            <i class="fa fa-minus"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 第二行：上次输入值和工时时间显示 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                <!-- 上次输入值显示 -->
                <div class="flex flex-col">
                    <label for="lastInputValue" class="text-sm text-gray-600 mb-1 text-center">上次输入值</label>
                    <div id="lastInputValue" class="app-display-box" data-value="0">0</div>
                </div>

                <!-- 工时时间显示 -->
                <div class="flex flex-col">
                    <label for="ratioCount" class="text-sm text-gray-600 mb-1 text-center">工时时间显示</label>
                    <div id="ratioCount" class="app-ratio-box" data-value="0.00">0.00</div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="mb-6">
            <label for="numberInput" class="block text-gray-600 mb-2 text-sm">输入非负整数（按回车确认）：</label>
            <input
                type="text"
                id="numberInput"
                class="app-input-field w-full"
                placeholder="请输入非负整数"
                inputmode="numeric"
            >
        </div>

        <!-- 按钮区域 -->
        <div class="flex flex-col sm:flex-row gap-4">
            <button id="resetBtn" class="app-btn-primary flex-1 flex items-center justify-center">
                <i class="fa fa-refresh mr-2"></i> 清零
            </button>
            <button id="copyBtn" class="app-btn-secondary flex-1 flex items-center justify-center">
                <i class="fa fa-copy mr-2"></i> 复制
            </button>
        </div>

        <!-- 用于辅助复制的隐藏文本区域 -->
        <textarea id="copyHelper" class="hidden absolute"></textarea>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<script>
    // 确保DOM完全加载
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const boxCountEl = document.getElementById('boxCount');
        const errorCountEl = document.getElementById('errorCount');
        const frameCountEl = document.getElementById('frameCount');
        const ratioCountEl = document.getElementById('ratioCount');
        const lastInputValueEl = document.getElementById('lastInputValue');
        const numberInput = document.getElementById('numberInput');
        const resetBtn = document.getElementById('resetBtn');
        const copyBtn = document.getElementById('copyBtn');
        const copyHelper = document.getElementById('copyHelper');
        const toast = document.getElementById('toast');
        const boxMinusBtn = document.getElementById('boxMinusBtn');
        const frameMinusBtn = document.getElementById('frameMinusBtn');
        const backButton = document.getElementById('backButton');

        // 初始化计数器值
        let boxCount = 0;
        let errorCount = 0;
        let frameCount = 0;
        let ratioCount = 0.00;
        let lastInputValue = 0;

        // 从本地存储加载数据
        function loadFromLocalStorage() {
            try {
                const savedData = localStorage.getItem('countAppData');
                if (savedData) {
                    const { box, error, frame, lastInput } = JSON.parse(savedData);

                    // 验证加载的数据是否有效
                    if (typeof box === 'number' && box >= 0 &&
                        typeof error === 'number' && error >= 0 &&
                        typeof frame === 'number' && frame >= 0 &&
                        (lastInput === undefined || (typeof lastInput === 'number' && lastInput >= 0))) {

                        boxCount = box;
                        errorCount = error;
                        frameCount = frame;
                        lastInputValue = lastInput || 0;
                        showToast('已加载保存的数据', 'info');
                        return true;
                    }
                }
            } catch (err) {
                console.error('加载本地数据失败:', err);
                showToast('加载保存的数据失败', 'error');
            }
            return false;
        }

        // 保存数据到本地存储
        function saveToLocalStorage() {
            try {
                const data = {
                    box: boxCount,
                    error: errorCount,
                    frame: frameCount,
                    lastInput: lastInputValue
                };
                localStorage.setItem('countAppData', JSON.stringify(data));
            } catch (err) {
                console.error('保存数据到本地失败:', err);
                showToast('保存数据失败', 'error');
            }
        }

        // 更新显示框并保存数据
        function updateDisplays() {
            boxCountEl.textContent = boxCount;
            boxCountEl.dataset.value = boxCount;

            errorCountEl.textContent = errorCount;
            errorCountEl.dataset.value = errorCount;

            frameCountEl.textContent = frameCount;
            frameCountEl.dataset.value = frameCount;

            lastInputValueEl.textContent = lastInputValue;
            lastInputValueEl.dataset.value = lastInputValue;

            // 计算并更新比例值
            ratioCount = boxCount / 275;
            const ratioFormatted = ratioCount.toFixed(2);
            ratioCountEl.textContent = ratioFormatted;
            ratioCountEl.dataset.value = ratioFormatted;

            // 更新后保存到本地存储
            saveToLocalStorage();
        }

        // 显示弹窗提示
        function showToast(message, type = 'info') {
            toast.classList.remove('success', 'error', 'info', 'show');
            toast.classList.add(type);
            toast.textContent = message;
            toast.classList.add('show');

            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 处理可编辑显示框的点击事件 - 转为输入框
        function makeEditable(element, valueType) {
            const currentValue = element.textContent;
            const input = document.createElement('input');
            input.type = 'text';
            input.className = 'app-edit-input';
            input.value = currentValue;
            input.autofocus = true;

            // 保存原始内容并替换为输入框
            element.dataset.originalContent = currentValue;
            element.textContent = '';
            element.appendChild(input);
            element.classList.add('app-display-box-editable');

            // 选中输入框内容
            input.select();

            // 处理输入框确认事件
            const handleConfirm = (newValue) => {
                // 验证输入是否为非负整数
                if (/^\d+$/.test(newValue) && parseInt(newValue) >= 0) {
                    const num = parseInt(newValue);

                    // 更新对应的值
                    if (valueType === 'box') {
                        boxCount = num;
                    } else if (valueType === 'frame') {
                        frameCount = num;
                    } else if (valueType === 'error') {
                        errorCount = num;
                    }

                    // 更新显示
                    updateDisplays();
                    showToast(`${valueType === 'box' ? '框数' : valueType === 'frame' ? '帧数' : '错误数'}已更新`, 'success');
                } else {
                    // 输入无效，恢复原始值
                    showToast(`请输入有效的非负整数`, 'error');
                }

                // 恢复显示框
                element.removeChild(input);
                element.classList.remove('app-display-box-editable');
                updateDisplays();
            };

            // 回车确认
            input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    handleConfirm(input.value.trim());
                } else if (e.key === 'Escape') {
                    // 按ESC取消编辑
                    element.removeChild(input);
                    element.classList.remove('app-display-box-editable');
                    element.textContent = element.dataset.originalContent;
                }
            });

            // 失去焦点确认
            input.addEventListener('blur', () => {
                handleConfirm(input.value.trim());
            });
        }

        // 为框数和帧数添加点击编辑功能
        boxCountEl.addEventListener('click', () => {
            makeEditable(boxCountEl, 'box');
        });

        frameCountEl.addEventListener('click', () => {
            makeEditable(frameCountEl, 'frame');
        });

        // 添加错误数的点击编辑功能
        errorCountEl.addEventListener('click', () => {
            makeEditable(errorCountEl, 'error');
        });

        // 框数减1按钮事件
        boxMinusBtn.addEventListener('click', () => {
            if (boxCount > 0) {
                boxCount -= 1;
                updateDisplays();
                showToast('框数已减1', 'info');

                // 添加动画效果
                boxCountEl.classList.add('border-blue-500', 'bg-blue-50');
                setTimeout(() => {
                    boxCountEl.classList.remove('border-blue-500', 'bg-blue-50');
                }, 500);
            } else {
                showToast('框数不能小于0', 'error');
                boxCountEl.classList.add('app-animate-shake');
                setTimeout(() => {
                    boxCountEl.classList.remove('app-animate-shake');
                }, 500);
            }
        });

        // 帧数减1按钮事件
        frameMinusBtn.addEventListener('click', () => {
            if (frameCount > 0) {
                frameCount -= 1;
                updateDisplays();
                showToast('帧数已减1', 'info');

                // 添加动画效果
                frameCountEl.classList.add('border-blue-500', 'bg-blue-50');
                setTimeout(() => {
                    frameCountEl.classList.remove('border-blue-500', 'bg-blue-50');
                }, 500);
            } else {
                showToast('帧数不能小于0', 'error');
                frameCountEl.classList.add('app-animate-shake');
                setTimeout(() => {
                    frameCountEl.classList.remove('app-animate-shake');
                }, 500);
            }
        });

        // 处理输入框回车事件
        numberInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                const inputValue = numberInput.value.trim();

                // 验证输入是否为非负整数
                if (/^\d+$/.test(inputValue) && parseInt(inputValue) >= 0) {
                    const num = parseInt(inputValue);

                    // 更新计数器
                    boxCount += num;
                    // 无论输入是否为0，都增加帧数
                    frameCount += 1;
                    // 保存上次输入值
                    lastInputValue = num;

                    // 更新显示
                    updateDisplays();

                    // 清空输入框并显示成功弹窗
                    numberInput.value = '';
                    showToast('更新成功！', 'success');

                    // 为显示框添加动画效果
                    [boxCountEl, frameCountEl, lastInputValueEl].forEach(el => {
                        el.classList.add('border-blue-500', 'bg-blue-50');
                        setTimeout(() => {
                            el.classList.remove('border-blue-500', 'bg-blue-50');
                        }, 500);
                    });

                    ratioCountEl.classList.add('border-purple-500', 'bg-purple-50');
                    setTimeout(() => {
                        ratioCountEl.classList.remove('border-purple-500', 'bg-purple-50');
                    }, 500);
                } else {
                    // 输入无效，显示错误弹窗
                    showToast('请输入有效的非负整数！', 'error');

                    // 添加错误动画
                    numberInput.classList.add('border-red-500', 'app-animate-shake');
                    setTimeout(() => {
                        numberInput.classList.remove('border-red-500', 'app-animate-shake');
                    }, 500);
                }

                // 聚焦回输入框
                numberInput.focus();
            }
        });

        // 清零按钮事件
        resetBtn.addEventListener('click', () => {
            // 重置所有计数器
            boxCount = 0;
            errorCount = 0;
            frameCount = 0;
            ratioCount = 0.00;
            lastInputValue = 0;

            // 更新显示
            updateDisplays();

            // 清空输入框
            numberInput.value = '';

            // 显示提示弹窗
            showToast('已重置所有计数器！', 'info');

            // 添加重置动画
            [boxCountEl, errorCountEl, frameCountEl, lastInputValueEl].forEach(el => {
                el.classList.add('border-gray-400', 'bg-gray-50');
                setTimeout(() => {
                    el.classList.remove('border-gray-400', 'bg-gray-50');
                }, 500);
            });

            ratioCountEl.classList.add('border-gray-400', 'bg-gray-50');
            setTimeout(() => {
                ratioCountEl.classList.remove('border-gray-400', 'bg-gray-50');
            }, 500);

            // 聚焦到输入框
            numberInput.focus();
        });

        // 复制按钮事件
        copyBtn.addEventListener('click', async () => {
            try {
                // 创建表格数据
                const tableData = `${boxCount}\t${errorCount}\t${frameCount}\t${ratioCount.toFixed(2)}`;

                // 尝试使用剪贴板API
                if (navigator.clipboard && window.isSecureContext) {
                    await navigator.clipboard.writeText(tableData);
                    showToast('已复制到剪贴板！', 'success');
                } else {
                    // fallback 方法
                    copyHelper.value = tableData;
                    copyHelper.select();
                    copyHelper.setSelectionRange(0, 99999);

                    document.execCommand('copy');
                    showToast('已复制到剪贴板！', 'success');
                }

                // 复制成功动画
                copyBtn.classList.add('bg-green-600');
                setTimeout(() => {
                    copyBtn.classList.remove('bg-green-600');
                }, 500);
            } catch (err) {
                // 复制失败处理
                showToast(`复制失败，请手动复制：${boxCount} ${errorCount} ${frameCount} ${ratioCount.toFixed(2)}`, 'error');
                console.error('复制失败:', err);
            }
        });

        // 限制输入框只能输入数字
        numberInput.addEventListener('input', (e) => {
            e.target.value = e.target.value.replace(/[^\d]/g, '');
        });

        // 返回按钮事件
        backButton.addEventListener('click', () => {
            window.history.back();
        });

        // 初始化页面
        const loaded = loadFromLocalStorage();
        if (!loaded) {
            showToast('使用初始数据', 'info');
        }
        updateDisplays();
        numberInput.focus();
    });
</script>
{% endblock %}
